import { readJson, writeJSON } from '../util/PromiseJson.js'
import path from 'path'
import __dirname from '../util/dirname.js'
import fs from 'fs'
import { promisify } from 'util'
const readdir = promisify(fs.readdir)

const database = path.resolve(__dirname, '../data/weapon/weapon.json')
const textrueDir = path.resolve(__dirname, '../assets/images/weapon')
const sprite_templete = '/assets/images/weapon/'

const getWeaponsByPage = async (req, res) => {
  const { page, size , search } = req.query
  let robots = await readJson(database)

  if(search){
    robots = robots.filter(e=>e.name.includes(search))
  }

  const start = (page - 1) * size
  let end = start + size
  end = end >= robots.length ? robots.length : end
  const sub = robots.slice(start, end)
  
  sub.forEach(e => {
    e.sprite = res.res_baseUrl + sprite_templete + e.sprite
  })

  res.send({ code: 200, msg: 'ok', data: sub, total: robots.length, next: parseInt(page) + 1 })
}

const textruePath = '/assets/images/weapon/'
const getWeaponTextrues = async (req, res) => {
  const result = await readdir(textrueDir)
  // console.log(result);
  const data = result.map(e => res.res_baseUrl + textruePath + e)
  res.send({
    code: 200,
    msg: 'ok',
    data
  })
}

const saveWeaponData = async (req, res) => {
  // console.log(req.body)
  const {data} = req.body
  const weapons = await readJson(database)
  if(data.id || data.id === 0){
    // Update
    let target = weapons.find(e=>e.id === data.id)
    data.sprite = data.sprite.slice(data.sprite.lastIndexOf('/'))
    Object.assign(target,data)
    await writeJSON(database,JSON.stringify(weapons))
  }else {
    // add
  }
  res.send({ code: 200, msg: 'ok', data: { success: true } })
}

export { getWeaponsByPage, getWeaponTextrues, saveWeaponData }